<script setup>
import { ref } from 'vue'

import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { userUpdateUserService } from '@/api/user.js'

// 直接使用store中的数据作为初始值，无需使用响应式，直接结构即可
const {
  user: { id, username, nickname, email },
  getUser
} = useUserStore()
// 定义表单数据
const form = ref({
  id,
  username,
  nickname,
  email
})

// 定义表单引用
const formRef = ref()

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称长度必须在2-10个字符之间且不能包含空格',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 提交表单
const onSubmit = async () => {
  await formRef.value?.validate()
  // 校验通过后发起请求
  await userUpdateUserService(form.value)
  await getUser()
  ElMessage.success('更新成功')
}
</script>

<template>
  <page-container title="基本资料">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      style="width: 400px; margin-top: 20px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="form.username" disabled />
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
      </el-form-item>

      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入用户邮箱" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
